package com.watchthelan.service.administrator;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.watchthelan.domain.Administrator;

public class AdministratorValidator implements Validator {

	@SuppressWarnings("unchecked")
	@Override
	public boolean supports(Class clazz) {
		return Administrator.class.equals(clazz);
	}

	@Override
	public void validate(Object object, Errors errors) {
		Administrator administrator = (Administrator) object;
		// Validate username
		if (!com.watchthelan.util.Validator.validUsername(administrator.getUsername())) {
			errors.rejectValue("username", "error.administrator.username", null, "Value required");
		}
		ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {
                "../applicationContext.xml"});
		AdministratorManager administratorManager = (AdministratorManager) ctx.getBean("administratorManager");
		Administrator adm = administratorManager.getAdministratorByUsername(administrator.getUsername());
		if (adm != null && administrator.getId() != adm.getId()) {
			errors.rejectValue("username", "error.administrator.username.exists", null, "Value required.");
		}
		// Validate name
		if ("".equals(administrator.getName())) {
			errors.rejectValue("name", "error.administrator.name", null, "Value required.");
		}
		// Validate phone (if exists)
		if (!"".equals(administrator.getPhone())
				&& !com.watchthelan.util.Validator.validPhone(administrator.getPhone())) {
			errors.rejectValue("phone", "error.administrator.phone", null, "Value required.");
		}
		// Validate email
		if (!com.watchthelan.util.Validator.validEmail(administrator.getEmail())) {
			errors.rejectValue("email", "error.administrator.email", null, "Value required.");
		}
	}

}
